package com.cts.tmall.app.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cts.tmall.app.request.R;
import com.cts.tmall.biz.service.GoodsService;
import com.cts.tmall.biz.service.PropService;
import com.cts.tmall.biz.service.SkuService;
import com.cts.tmall.biz.service.SpecService;
import com.cts.tmall.dal.entity.Goods;
import com.cts.tmall.dal.entity.Prop;
import com.cts.tmall.dal.entity.Sku;
import com.cts.tmall.dal.entity.Spec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/goods")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @Autowired
    PropService propService;

    @Autowired
    SkuService skuService;

    @Autowired
    SpecService specService;

    @GetMapping("init")
    public R init() {
        removeUndo();
        Goods goods = new Goods();
        Snowflake snowflake = IdUtil.createSnowflake(1L, 1L);
        String no = String.valueOf(snowflake.nextId());
        goods.setGoodsNo(no);
        goods.setStatus(99);
        goodsService.save(goods);
        return R.ok().put("goodsNo", no);
    }

    /**
     * 删除未录入的数据
     * todo 应用到项目中，查询条件添加用户判断，防止删除他人数据
     */
    private void removeUndo() {
        List<Goods> list = goodsService.list(new QueryWrapper<Goods>().eq("status", 99));
        if (list.size() == 0) {
            return;
        }
        for (Goods goods : list) {
            propService.remove(new QueryWrapper<Prop>().eq("goods_no", goods.getGoodsNo()));
            skuService.remove(new QueryWrapper<Sku>().eq("goods_no", goods.getGoodsNo()));
            specService.remove(new QueryWrapper<Spec>().eq("goods_no", goods.getGoodsNo()));
        }
        goodsService.remove(new QueryWrapper<Goods>().eq("status", 99));
    }
}
